package controller

import (
	"fmt"
	Log "hello/Log"
	logic "hello/logic"
	Model "hello/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

func SignUpHandler(c *gin.Context) {
	p := new(Model.SignUpParam)
	//1.参数校验
	if err := c.ShouldBindJSON(p); err != nil {
		Log.Logger.Error("参数校验错误日志", zap.Error(err))
		//判断err类型是不是validator.validationerrors
		err, ok := err.(validator.ValidationErrors)
		if !ok {
			RespnseErr(c, CodeInvalidParam)
			return
		}

		RespnseErrWithMsg(c, CodeInvalidParam, removeTopStruct(err.Translate(trans)))
		return
	}

	// if (len(p.Passwd) == 0 || len(p.Repasswd) == 0 || len(p.UserName)==0 || p.Repasswd != p.Passwd)
	// {
	// 	Log.Logger.Error("参数校验错误日志", zap.Error(err))
	// 	c.JSON(http.StatusOK, gin.H{
	// 		"msg": "请求参数有误",
	// 	})

	// 	return
	// }

	fmt.Println(p)

	//业务处理
	if err := logic.SignUp(p); err != nil {
		zap.L().Error("logic.signup failed", zap.Error(err))
		RespnseErr(c, CodeUserExist)
		return
	}

	//返回响应
	c.JSON(http.StatusOK, "ok")
}

func LoginHandler(c *gin.Context) {
	//获取请求参数及参数校验
	p := new(Model.LoginParam)

	//参数校验
	if err := c.ShouldBindJSON(p); err != nil {
		Log.Logger.Error("login failed with invaid para", zap.Error(err))
		//判断err类型是不是validator.validationerrors
		err, ok := err.(validator.ValidationErrors)
		if !ok {
			c.JSON(http.StatusOK, gin.H{
				"msg": err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"msg": removeTopStruct(err.Translate(trans)), //翻译错误
		})

		return
	}

	token, err := logic.Login(p)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "用户名或者密码错误",
		})

		return
	}

	RespnseSuccess(c, token)
}
